package com.fjrz.bbxwj.main.host

import android.text.SpannableString
import android.text.Spanned
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.view.View
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.*
import com.module.lemlin.mode.ViewModeFragment
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.msg
import com.fjrz.bbxwj.R
import com.fjrz.bbxwj.app.RZApplication
import com.fjrz.bbxwj.entity.VideoCateList
import com.fjrz.bbxwj.listener.TabSelectedListener
import com.fjrz.bbxwj.main.access.AccessActivity
import com.fjrz.bbxwj.main.host.adpter.ViewPager2Adapter
import com.fjrz.bbxwj.main.host.side.MainRichTextActivity
import com.fjrz.bbxwj.mode.vm.VideoViewModel
import com.fjrz.bbxwj.popup.VideoCategoryPopup
import com.fjrz.bbxwj.util.AudioMngHelper
import com.google.android.material.tabs.TabLayoutMediator
import com.module.lemlin.rxhttp.code
import com.module.lemlin.view.DialogHintPopup
import com.module.lemlin.view.LoginAuthPopup
import kotlinx.android.synthetic.main.fragment_main_home.*
import java.lang.StringBuilder

class MainHomeFragment : ViewModeFragment<VideoViewModel>() {

    companion object {
        fun newInstance(): MainHomeFragment {
            return MainHomeFragment()
        }
    }

    private val mVideoCategoryPopup: VideoCategoryPopup by lazy {
        VideoCategoryPopup(context = requireContext(), onConfirmTotal = { _, _, videoCate ->
            val videoCateList: MutableList<VideoCateList> =
                mViewPager2Adapter.getVideoCateLists()
                    .filter { it.id != -1 && it.id != -2 && it.id != videoCate.id }
                    .toMutableList()
            val cateIds = StringBuilder()
            videoCateList.forEach {
                cateIds.append(it.id).append(",")
            }
            //cateIds.deleteCharAt((cateIds.length-1))
            viewModel.videoSetCate(cateIds.toString(), videoCate, type = 2)
        }, onConfirmDefault = { _, _, videoCate ->
            val videoCateList: MutableList<VideoCateList> =
                mViewPager2Adapter.getVideoCateLists().filter { it.id != -1 && it.id != -2 }
                    .toMutableList()
            if (videoCateList.find { it.id == videoCate.id } != null)
                return@VideoCategoryPopup
            videoCateList.add(videoCate)
            val cateIds = StringBuilder()
            videoCateList.forEach {
                cateIds.append(it.id).append(",")
            }
            cateIds.deleteCharAt((cateIds.length - 1))
            viewModel.videoSetCate(cateIds.toString(), videoCate, type = 1)
        })
    }

    private val mViewPager2Adapter: ViewPager2Adapter by lazy {
        ViewPager2Adapter(fragment = this)
    }


    private val userAgreePopup: DialogHintPopup by lazy {
        DialogHintPopup(context = requireContext(),
            onConfirm = {
                userAgreePopup.dismiss()
                viewModel.videoDefaultCateList()
                SPStaticUtils.put("SPS_USER_AGREE", true)
            },
            onCancel = {
                userAgreePopup.dismiss()
                SPStaticUtils.put("SPS_USER_AGREE", false)
                requireActivity().finish()
            })
    }

    override fun viewModel(): VideoViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.fragment_main_home

    override fun initView() {

        BarUtils.addMarginTopEqualStatusBarHeight(llMainHomeBar)

        vp2MainHomeVideo.adapter = mViewPager2Adapter

        tabMainHomeCategory.addOnTabSelectedListener(
            TabSelectedListener(requireContext(), R.color.white)
        )

        TabLayoutMediator(tabMainHomeCategory, vp2MainHomeVideo) { tab, position ->
            mViewPager2Adapter.getVideoCateLists().let {
                tab.text = it[position].name
            }
        }.attach()

        ivMainHomeCategory.setOnClickListener {
            viewModel.videoCateTotalList()
        }


    }

    override fun initData() {

        val isUserAgree: Boolean = SPStaticUtils.getBoolean("SPS_USER_AGREE")
        if (!isUserAgree) {
            val content = "尊敬的倍倍星用户：我们尊重并保护您的个人隐私，为保障您的权益，" +
                    "请在注册登录前完整阅读并充分理解《用户协议》和《隐私协议》以帮助您了解维护自己隐私权的方式，" +
                    "一但您开始使用本软件服务，我们将按照上述内容中约定的权利和义务来处理您的个人信息。点击“同意”即表示您已阅读并接受上述内容之约定条款，" +
                    "然后我们将继续为您服务。"
            userAgreePopup.setTextTitle("用户协议和隐私政策")
                //.setTextUserAgree(getSpannableStringUserAgree("你可阅读《用户协议》和《隐私协议》了解详细信息。如你同意，请点击同意开始接受我们的服务。"))
                .setTextUserAgree(getSpannableStringUserAgree(content))
                .setTextCancel("不同意")
                .setTextConfirm("同意")
                .setBackPressEnable(false)
                .setOutSideDismiss(false)
                .showPopupWindow()
        } else {
            viewModel.videoDefaultCateList()
        }
    }

    private fun getSpannableStringUserAgree(agrees: String): SpannableString {
        val spannable = SpannableString(agrees)
        spannable.setSpan(
            object : ClickableSpan() {
                override fun onClick(widget: View) {
                    MainRichTextActivity.open(
                        activity = requireActivity(),
                        title = "用户协议",
                        name = "user_agreement_text"
                    )
                }

                override fun updateDrawState(ds: TextPaint) {
                    super.updateDrawState(ds)
                    ds.color = ColorUtils.getColor(R.color.colorMain)
                    ds.isUnderlineText = false
                }
            },
            agrees.indexOf(string = "《"),
            agrees.indexOf(string = "》") + 1,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        spannable.setSpan(
            object : ClickableSpan() {
                override fun onClick(widget: View) {
                    MainRichTextActivity.open(
                        activity = requireActivity(),
                        title = "隐私协议",
                        name = "privacy_policy_text"
                    )
                }

                override fun updateDrawState(ds: TextPaint) {
                    super.updateDrawState(ds)
                    ds.color = ColorUtils.getColor(R.color.colorMain)
                    ds.isUnderlineText = false
                }
            },
            agrees.lastIndexOf(string = "《"),
            agrees.lastIndexOf(string = "》") + 1,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        return spannable
    }

    override fun initViewMode() {
        viewModel.videoCateDefaultListLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.code, response.throwable?.msg)
            if (response.status != Status.SUCCESS)
                return@Observer
            val videoCateLists: MutableList<VideoCateList> = response.httpData?.data
                ?: return@Observer
            videoCateLists.removeAll(mViewPager2Adapter.getVideoCateLists())
            mViewPager2Adapter.addALL(videoCateLists)
            mVideoCategoryPopup.setFillDataCateListDefault(videoCateLists)
            tabMainHomeCategory.getTabAt(1)?.select()
        })

        viewModel.videoCateTotalListLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.code, response.throwable?.msg)
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.data?.let {
                mVideoCategoryPopup.setFillDataCateListTotal(it)
                    .setFillDataCateListDefault(mViewPager2Adapter.getVideoCateLists())
                    .showPopupWindow()
            }
        })

        viewModel.videoSetCateLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.code, response.throwable?.msg)
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.let { set ->
                set.videoCateList?.let {
                    if (set.type == 1) {
                        mViewPager2Adapter.add(it)
                    }
                    if (set.type == 2) {
                        mViewPager2Adapter.remove(it)
                    }
                    mVideoCategoryPopup.setFillDataCateListDefault(mViewPager2Adapter.getVideoCateLists())
                }
            }
        })
    }

    override fun onEventMainThread(any: Any) {
        if (any !is LoginAuthPopup.Action)
            return
        if (any == LoginAuthPopup.Action.ACTION_LOGIN_SUCCESS) {
            initData()
        }
    }

}